package net.xdclass.utils;


import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.LoginUser;

import java.util.Date;

@Data
@Slf4j
public class JWTUtil {


    /**
     * 主题
     */

    public static final String SUBJECT = "xdclass";

    /**
     * 加密秘钥
     */
    public static final String SECRET = "xdclass.net168";

    /**
     * 令牌前缀
     */
    public static final String TOKEN_PREFIX = "dcloud-link";

    /**
     * 7天时间有效
     */
    private static final Long EXPIRE = 1000 * 60 * 60 * 24 * 7L;
    /**
     * 生成token
     * @param loginUser
     * @return
     */
    public static String createJWTToken(LoginUser loginUser) {

        if (loginUser == null) {
            throw new NullPointerException("对象为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                //配置payload
                .claim("head_img", loginUser.getHeadImg())
                .claim("account_no", loginUser.getAccountNo())
                .claim("username", loginUser.getUsername())
                .claim("phone", loginUser.getPhone())
                .claim("mail", loginUser.getMail())
                .claim("auth", loginUser.getAuth())
                //发布时间
                .setIssuedAt(new Date())
                .setExpiration(new Date(CommonUtil.getCurrentTimestamp() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    /**
     * 解密 jwt
     * @param token
     * @return
     */
    public  static Claims checkJWT(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws
                            (token.replace(TOKEN_PREFIX, "")).getBody();
            return claims;
        } catch (Exception e) {
           log.error("jwt 解密失败");
            return null;
        }
    }

}
